import 'dart:isolate';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:spring_fairy/api/api.dart';
import 'package:spring_fairy/api/user_store.dart';
import 'package:spring_fairy/background_task.dart';
import 'package:spring_fairy/model/config.dart';
import 'package:spring_fairy/pages/login_page.dart';
import 'package:spring_fairy/pages/record_mood_track_page.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart'
    show BMFMapSDK, BMF_COORD_TYPE;
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
//deepseek:sk-301cb392cba84ff8b0162c1ee1a42f4a

//http://www.moncci.com/Blog/Detail?id=72

/**
 *  主页：地图页面
 *  查看历史轨迹页面
 *  admin
 */


void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  BMFMapSDK.setAgreePrivacy(true);
  await BMFAndroidVersion.initAndroidVersion();
  BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);


  try {
    await UserStore.readFromFile();
  } catch(_) {}


  runApp(const MyApp());

  initializeService();
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: AppConfig.PRIMARY_COLOR),
        fontFamily: 'Smiley Sans'
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});


  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const String _isolateName = "LocatorIsolate";
  ReceivePort port = ReceivePort();


  @override
  void initState() {
    super.initState();
    //处理登录
    UserStore.onLoginStateChange = () async {
      await UserStore.saveToFile();
      API.token = UserStore.token;
      setState(() {
        if(UserStore.user != null && UserStore.token != null) {
          UserStore.hasLogin = true;
        }
      });
    };

    IsolateNameServer.registerPortWithName(port.sendPort, _isolateName);
    port.listen((dynamic data) {
      // do something with data
    });
  }


  @override
  Widget build(BuildContext context) {
   return UserStore.hasLogin
        ? RecordMoodTrackPage()
        : LoginPage();
  }
}
